package com.sub.framework.config;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties;
import com.alibaba.druid.util.Utils;
import com.sub.common.utils.spring.SpringUtils;
import com.sub.framework.aspectj.lang.enums.DataSourceType;
import com.sub.framework.config.properties.DruidProperties;
import com.sub.framework.datasource.DynamicDataSource;

/**
 * druid 配置多数据源
 * 
 * @author ruoyi
 */
@Configuration
public class DruidConfig
{

    @Bean
    @ConfigurationProperties("spring.datasource.druid.master")
    public DataSource masterDataSource(DruidProperties druidProperties)
    {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }

    @Bean
    @ConfigurationProperties("spring.datasource.druid.slave")
    @ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true")
    public DataSource slaveDataSource(DruidProperties druidProperties)
    {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }

    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dataSource(DataSource masterDataSource)
    {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);
        setDataSource(targetDataSources, DataSourceType.SLAVE.name(), "slaveDataSource");
        return new DynamicDataSource(masterDataSource, targetDataSources);
    }

    /**
     * 设置数据源
     *
     * @param targetDataSources 备选数据源集合
     * @param sourceName 数据源名称
     * @param beanName bean名称
     */
    public void setDataSource(Map<Object, Object> targetDataSources, String sourceName, String beanName)
    {
        try
        {
            DataSource dataSource = SpringUtils.getBean(beanName);
            targetDataSources.put(sourceName, dataSource);
        }
        catch (Exception e)
        {
        }
    }
//@Bean
//@Primary
//public DataSource shardingDataSource() throws SQLException {
//
//    ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
//    //用户表配置，可以添加多个配置
//    shardingRuleConfig.getTableRuleConfigs().add(getUserTableRuleConfiguration());
////        shardingRuleConfig.getTableRuleConfigs().add(getUserTableRuleConfiguration1());
//    shardingRuleConfig.getBindingTableGroups().add("oms_order");
//    //设置数据库策略，传入的是sys_time
//    // 设置数据表策略，传入的是payment_time
//    shardingRuleConfig.setDefaultTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("payment_time",new CreateTimeShardingAlgorithm()));
//
//    ShardingRule shardingRule = new ShardingRule(shardingRuleConfig, Collections.singleton("m1"));
//    Properties properties = new Properties();
//    properties.put("sql-show",true);
//    return new ShardingDataSource(createDataSourceMap(),shardingRule,properties);
//
//}
//    //创建用户表规则
//    @Bean
//    TableRuleConfiguration getUserTableRuleConfiguration() {
//        TableRuleConfiguration orderTableRuleConfig = new TableRuleConfiguration("oms_order","m1.oms_order_$->{2020}_$->{9..10}");
//        KeyGeneratorConfiguration keyGeneratorConfiguration= new KeyGeneratorConfiguration("SNOWFLAKE","id");
//        orderTableRuleConfig.setKeyGeneratorConfig(keyGeneratorConfiguration);
//        return orderTableRuleConfig;
//    }
//
//    @Bean
//    TableRuleConfiguration getUserTableRuleConfiguration1() {
//        TableRuleConfiguration orderTableRuleConfig = new TableRuleConfiguration("oms_order","m1.oms_order_$->{2020}_$->{9..10}");
//        return orderTableRuleConfig;
//    }
//
//
//    //下面函数是获取数据源，即包含有多少个数据库，读入到系统中存放于map中
//    private Map<String, DataSource> createDataSourceMap() {
//        Map<String, DataSource> result = new HashMap<>();
//        result.put("m1", createDataSource("jdbc:mysql://sunbird.top:3306/ry_vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8"));
////        result.put("db_201810", createDataSource("jdbc:mysql://localhost:3306/db_201810?characterEncoding=utf8&useSSL=false"));
////        result.put("db_201811", createDataSource("jdbc:mysql://localhost:3306/db_201811?characterEncoding=utf8&useSSL=false"));
//        return result;
//    }
//
//    private DataSource createDataSource(final String dataSourceName) {
//        //使用默认连接池
//        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
////        return druidProperties.dataSource(dataSource);
////        DataS result = new BasicDataSource();
//        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
//        //设置数据库路径
//        dataSource.setUrl(dataSourceName);
//        //设置数据库用户名
//        dataSource.setUsername("root");
//        //设置数据密码
//        dataSource.setPassword("root");
//
//        return dataSource;
//    }
    /**
     * 去除监控页面底部的广告
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Bean
    @ConditionalOnProperty(name = "spring.datasource.druid.statViewServlet.enabled", havingValue = "true")
    public FilterRegistrationBean removeDruidFilterRegistrationBean(DruidStatProperties properties)
    {
        // 获取web监控页面的参数
        DruidStatProperties.StatViewServlet config = properties.getStatViewServlet();
        // 提取common.js的配置路径
        String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*";
        String commonJsPattern = pattern.replaceAll("\\*", "js/common.js");
        final String filePath = "support/http/resources/js/common.js";
        // 创建filter进行过滤
        Filter filter = new Filter()
        {
            @Override
            public void init(javax.servlet.FilterConfig filterConfig) throws ServletException
            {
            }
            @Override
            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                    throws IOException, ServletException
            {
                chain.doFilter(request, response);
                // 重置缓冲区，响应头不会被重置
                response.resetBuffer();
                // 获取common.js
                String text = Utils.readFromResource(filePath);
                // 正则替换banner, 除去底部的广告信息
                text = text.replaceAll("<a.*?banner\"></a><br/>", "");
                text = text.replaceAll("powered.*?shrek.wang</a>", "");
                response.getWriter().write(text);
            }
            @Override
            public void destroy()
            {
            }
        };
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(filter);
        registrationBean.addUrlPatterns(commonJsPattern);
        return registrationBean;
    }


}
